<?php
defined('APP_PATH') or die ('Unauthorized access');
/**
 * http 请求类
 */
class Ext_Httprequest
{
	public $useragent = 'WP mvc';
	public $connecttimeout = 30;
	public $timeout = 30;
	public $ssl_verifer = FALSE;
	
	/**
	 * 请求
	 * @param unknown_type $url
	 * @param unknown_type $method
	 * @param unknown_type $params
	 */
	public function http($url,$method,$params = '')
	{
		//获取请求地址
		if(!empty($params)){
			if(strpos($url,'?') !== FALSE){
				if(is_array($params)){
					foreach($params as $k => $v){
						$url .= '&'.$k.'='.$v;
					}
				}else{
					$url = $url.'&'.$params;
				}
			}else{
				if(is_array($params)){
					$url = $url.'?';
					foreach($params as $k => $v){
						$url .= $k.'='.$v.'&';
					}
					$url = substr($url,0,-1);
				}else{
					$url = $url.'?'.$params;
				}
			}
		}
		
		if(function_exists('curl_init')){
			$ci = curl_init();
			
			curl_setopt($ci, CURLOPT_USERAGENT, $this->useragent); 
			curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $this->connecttimeout); 
			curl_setopt($ci, CURLOPT_TIMEOUT, $this->timeout); 
			curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE); 
	
			curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, $this->ssl_verifer); 
	
			curl_setopt($ci, CURLOPT_HEADERFUNCTION, array($this, 'getHeader')); 
	
			curl_setopt($ci, CURLOPT_HEADER, FALSE);
			
			curl_setopt($ci, CURLOPT_URL, $url);
			
			$result = curl_exec($ci);
			curl_close($ci);
			
			
		}else{
			$context = array('http' =>array('method' => 'POST',
							'header' => 'Content-type: application/x-www-form-urlencoded'."\r\n".
										'User-Agent: WP MVC '."\r\n".
										'Content-length: ' . strlen($url),
							'content' => $url));
			$contextid = stream_context_create($context);
			$sock= fopen($url, 'r', false, $contextid);
			if ($sock) {
				$result='';
				while (!feof($sock))
					$result.=fgets($sock, 4096);
				fclose($sock);
			}

		}
		
		return $result;
		
		
	}
	
	public function getHeader($ch, $header) 
	{ 
		$i = strpos($header, ':'); 
		if (!empty($i)) { 
			$key = str_replace('-', '_', strtolower(substr($header, 0, $i))); 
			$value = trim(substr($header, $i + 2)); 
			$this->http_header[$key] = $value; 
		} 
		return strlen($header); 
    }
	
}